// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化PPT预览功能
    initPresentation();

    // 初始化评论功能
    initComments();

    // 初始化返回顶部按钮
    initBackToTop();

    // 初始化导航高亮
    initNavHighlight();

    // 初始化响应式布局
    initResponsiveLayout();

    // 初始化平滑滚动功能
    initSmoothScroll();
});

// 初始化平滑滚动功能
function initSmoothScroll() {
    // 为所有内部链接添加平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            // 确保链接指向的是页面内的锚点
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                e.preventDefault();

                // 计算目标位置，考虑固定导航栏的高度
                const headerOffset = 80; // 与CSS中的scroll-padding-top保持一致
                const elementPosition = targetElement.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                // 执行平滑滚动
                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });

                // 更新URL但不刷新页面
                history.pushState(null, null, targetId);
            }
        });
    });

    // 监听浏览器前进/后退按钮，保持平滑滚动
    window.addEventListener('popstate', function() {
        const targetId = window.location.hash;
        if (targetId) {
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                setTimeout(() => {
                    const headerOffset = 80;
                    const elementPosition = targetElement.getBoundingClientRect().top;
                    const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

                    window.scrollTo({
                        top: offsetPosition,
                        behavior: 'smooth'
                    });
                }, 10);
            }
        }
    });

    // 增强版滚动监听，用于高亮当前活跃的锚点
    const sections = document.querySelectorAll('section, div[id]');

    window.addEventListener('scroll', throttle(function() {
        let currentActiveSection = '';

        sections.forEach(section => {
            const sectionTop = section.offsetTop - 100;
            const sectionHeight = section.offsetHeight;

            if (pageYOffset >= sectionTop && pageYOffset < sectionTop + sectionHeight) {
                currentActiveSection = '#' + section.getAttribute('id');
            }
        });

        // 更新导航高亮
        document.querySelectorAll('.course-nav-link').forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === currentActiveSection) {
                link.classList.add('active');
            }
        });
    }, 100));
}

// 初始化PPT预览功能
function initPresentation() {
    const slides = document.querySelectorAll('.slide');
    const prevBtn = document.querySelector('.prev-btn');
    const nextBtn = document.querySelector('.next-btn');
    const pagination = document.querySelector('.pagination');
    const thumbnails = document.querySelectorAll('.thumbnail-item');
    const previewThumbnails = document.querySelectorAll('.preview-thumbnail');
    const zoomInBtn = document.querySelector('#zoomIn');
    const zoomOutBtn = document.querySelector('#zoomOut');
    const zoomLevel = document.querySelector('#zoomLevel');
    const slidesContainer = document.querySelector('.slides-container');
    const presentationContainer = document.querySelector('.presentation-container');
    const fullscreenBtn = document.querySelector('#toggleFullscreen');

    let currentSlide = 0;
    let currentZoom = 100;

    // 显示当前幻灯片
    function showSlide(index) {
        // 隐藏所有幻灯片
        slides.forEach(slide => {
            slide.classList.remove('active');
        });

        // 激活指定幻灯片
        slides[index].classList.add('active');

        // 更新分页信息
        if (pagination) {
            pagination.textContent = `${index + 1}/${slides.length}`;
        }

        // 更新缩略图选中状态
        if (thumbnails.length > 0) {
            thumbnails.forEach(thumb => {
                thumb.classList.remove('active');
            });
            if (thumbnails[index]) {
                thumbnails[index].classList.add('active');
            }
        }

        // 更新右侧预览缩略图选中状态
        if (previewThumbnails.length > 0) {
            previewThumbnails.forEach(thumb => {
                thumb.classList.remove('active');
            });
            if (previewThumbnails[index]) {
                previewThumbnails[index].classList.add('active');
            }
        }

        currentSlide = index;
    }

    // 上一张幻灯片
    function goToPrevSlide() {
        currentSlide = (currentSlide - 1 + slides.length) % slides.length;
        showSlide(currentSlide);
    }

    // 下一张幻灯片
    function goToNextSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }

    // 缩放功能
    function zoomIn() {
        if (currentZoom < 150) {
            currentZoom += 10;
            updateZoom();
        }
    }

    function zoomOut() {
        if (currentZoom > 50) {
            currentZoom -= 10;
            updateZoom();
        }
    }

    function updateZoom() {
        if (slidesContainer) {
            slidesContainer.style.transform = `scale(${currentZoom / 100})`;
            slidesContainer.style.transformOrigin = 'center';
        }
        if (zoomLevel) {
            zoomLevel.textContent = `${currentZoom}%`;
        }
    }

    // 全屏功能
    function isFullscreen() {
        return document.fullscreenElement || document.webkitFullscreenElement;
    }
    function enterFullscreen() {
        if (presentationContainer && presentationContainer.requestFullscreen) {
            presentationContainer.requestFullscreen();
        } else if (presentationContainer && presentationContainer.webkitRequestFullscreen) {
            presentationContainer.webkitRequestFullscreen();
        }
    }
    function exitFullscreen() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
    function toggleFullscreen() {
        if (isFullscreen()) {
            exitFullscreen();
        } else {
            enterFullscreen();
        }
    }
    function updateFullscreenUI() {
        if (!fullscreenBtn) return;
        if (isFullscreen()) {
            fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i> 退出全屏';
        } else {
            fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i> 全屏';
        }
    }

    // 事件监听
    if (prevBtn) {
        prevBtn.addEventListener('click', goToPrevSlide);
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', goToNextSlide);
    }

    if (zoomInBtn) {
        zoomInBtn.addEventListener('click', zoomIn);
    }

    if (zoomOutBtn) {
        zoomOutBtn.addEventListener('click', zoomOut);
    }

    // 全屏事件
    if (fullscreenBtn) {
        fullscreenBtn.addEventListener('click', toggleFullscreen);
        document.addEventListener('fullscreenchange', updateFullscreenUI);
        document.addEventListener('webkitfullscreenchange', updateFullscreenUI);
    }

    // 缩略图点击事件
    if (thumbnails.length > 0) {
        thumbnails.forEach((thumb, index) => {
            thumb.addEventListener('click', () => {
                showSlide(index);
            });
        });
    }

    // 右侧预览缩略图点击事件
    if (previewThumbnails.length > 0) {
        previewThumbnails.forEach((thumb, index) => {
            thumb.addEventListener('click', () => {
                showSlide(index);
            });
        });
    }

    // 键盘导航
    document.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowLeft') {
            goToPrevSlide();
        } else if (e.key === 'ArrowRight') {
            goToNextSlide();
        }
    });

    // 初始化显示第一张幻灯片
    showSlide(0);
}

// 初始化评论功能
function initComments() {
    const submitBtn = document.querySelector('.submit-comment-btn');
    const commentTextarea = document.querySelector('.comment-textarea');
    const commentsList = document.querySelector('.comments-list');
    const loadMoreBtn = document.querySelector('.load-more-btn');
    const searchInput = document.querySelector('.search-input');
    const filterBtns = document.querySelectorAll('.filter-btn');

    // 提交评论
    if (submitBtn && commentTextarea) {
        submitBtn.addEventListener('click', function() {
            const commentText = commentTextarea.value.trim();
            if (commentText) {
                // 在实际应用中，这里会发送API请求保存评论
                // 这里仅做前端演示
                alert('评论已提交：\n内容：' + commentText);
                commentTextarea.value = '';
            }
        });
    }

    // 初始化单独的评分系统
    const ratingStarsLarge = document.querySelectorAll('.rating-stars-large i');
    const submitRatingBtn = document.querySelector('.submit-rating-btn');
    let selectedRating = 0;

    if (ratingStarsLarge.length > 0 && submitRatingBtn) {
        // 初始化提交按钮状态
        submitRatingBtn.disabled = true;

        ratingStarsLarge.forEach(star => {
            // 点击选择评分
            star.addEventListener('click', function() {
                const rating = parseInt(this.getAttribute('data-rating'));
                selectedRating = rating;

                // 更新星星显示状态
                ratingStarsLarge.forEach(s => {
                    const sRating = parseInt(s.getAttribute('data-rating'));
                    if (sRating <= rating) {
                        s.classList.remove('far');
                        s.classList.add('fas');
                        s.classList.add('active');
                    } else {
                        s.classList.remove('fas');
                        s.classList.remove('active');
                        s.classList.add('far');
                    }
                });

                // 启用提交按钮
                submitRatingBtn.disabled = false;
            });

            // 鼠标悬停效果
            star.addEventListener('mouseover', function() {
                const hoverRating = parseInt(this.getAttribute('data-rating'));

                ratingStarsLarge.forEach(s => {
                    const sRating = parseInt(s.getAttribute('data-rating'));
                    if (sRating <= hoverRating) {
                        s.classList.remove('far');
                        s.classList.add('fas');
                    } else if (sRating > selectedRating) {
                        s.classList.remove('fas');
                        s.classList.add('far');
                    }
                });
            });
        });

        // 鼠标离开时恢复当前评分状态
        const ratingContainer = document.querySelector('.rating-stars-large');
        if (ratingContainer) {
            ratingContainer.addEventListener('mouseleave', function() {
                ratingStarsLarge.forEach(s => {
                    const sRating = parseInt(s.getAttribute('data-rating'));
                    if (sRating <= selectedRating) {
                        s.classList.remove('far');
                        s.classList.add('fas');
                        s.classList.add('active');
                    } else {
                        s.classList.remove('fas');
                        s.classList.remove('active');
                        s.classList.add('far');
                    }
                });
            });
        }

        // 提交评分
        submitRatingBtn.addEventListener('click', function() {
            if (selectedRating > 0) {
                // 在实际应用中，这里会发送API请求保存评分
                // 这里仅做前端演示
                alert('评分已提交：\n' + '★'.repeat(selectedRating) + '☆'.repeat(5 - selectedRating));

                // 简单模拟更新平均评分（实际应用中应该从服务器获取）
                const averageScoreElem = document.querySelector('.average-score');
                if (averageScoreElem) {
                    const currentAvg = parseFloat(averageScoreElem.textContent);
                    // 简单计算新的平均分（实际应用中应该基于所有评分计算）
                    const newAvg = (currentAvg + selectedRating) / 2;
                    averageScoreElem.textContent = newAvg.toFixed(1);
                }
            }
        });
    }

    // 按Enter键提交评论
    if (commentTextarea) {
        commentTextarea.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (submitBtn) {
                    submitBtn.click();
                }
            }
        });
    }

    // 点赞功能
    const likeIcons = document.querySelectorAll('.action-btn-small i.fa-thumbs-up');
    likeIcons.forEach(icon => {
        const btn = icon.closest('button');
        if (btn) {
            btn.addEventListener('click', function() {
                const likeCount = this.querySelector('span');
                if (likeCount) {
                    let count = parseInt(likeCount.textContent);
                    if (icon.classList.contains('fas')) {
                        // 已点赞状态，取消点赞
                        count--;
                        icon.classList.remove('fas');
                        icon.classList.add('far');
                    } else {
                        // 未点赞状态，添加点赞
                        count++;
                        icon.classList.remove('far');
                        icon.classList.add('fas');
                    }
                    likeCount.textContent = count;
                }
            });
        }
    });

    // 回复功能
    const replyBtns = document.querySelectorAll('.action-btn-small.reply');
    replyBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 在实际应用中，这里会显示回复表单
            alert('回复功能已触发');
        });
    });

    // 加载更多评论
    if (loadMoreBtn) {
        loadMoreBtn.addEventListener('click', function() {
            // 在实际应用中，这里会加载更多评论
            alert('加载更多评论');
        });
    }

    // 搜索评论
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            // 在实际应用中，这里会根据搜索词过滤评论
            console.log('搜索评论：' + searchTerm);
        });
    }

    // 过滤评论
    if (filterBtns.length > 0) {
        filterBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                // 移除所有按钮的激活状态
                filterBtns.forEach(b => b.classList.remove('active'));
                // 添加当前按钮的激活状态
                this.classList.add('active');
                // 在实际应用中，这里会根据选择的过滤器过滤评论
                const filterType = this.getAttribute('data-filter');
                console.log('过滤评论：' + filterType);
            });
        });
    }
}

// 初始化返回顶部按钮
function initBackToTop() {
    const backToTopBtn = document.querySelector('.back-to-top');

    if (backToTopBtn) {
        // 监听滚动事件，显示/隐藏返回顶部按钮
        window.addEventListener('scroll', function() {
            if (window.pageYOffset > 300) {
                backToTopBtn.classList.add('visible');
            } else {
                backToTopBtn.classList.remove('visible');
            }
        });

        // 点击返回顶部
        backToTopBtn.addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });
    }
}

// 初始化导航高亮
function initNavHighlight() {
    const navLinks = document.querySelectorAll('.course-nav-link');

    if (navLinks.length > 0) {
        // 在实际应用中，这里会根据当前页面路径高亮对应的导航项
        // 这里默认高亮第一个导航项
        navLinks[0].classList.add('active');

        // 导航项点击事件
        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                // 移除所有导航项的激活状态
                navLinks.forEach(l => l.classList.remove('active'));
                // 添加当前导航项的激活状态
                this.classList.add('active');
                // 在实际应用中，这里会阻止默认跳转行为并处理页面内容切换
                // e.preventDefault();
            });
        });
    }
}

// 初始化响应式布局
function initResponsiveLayout() {
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        adjustLayout();
    });

    // 初始调整
    adjustLayout();

    function adjustLayout() {
        const windowWidth = window.innerWidth;
        const slidesContainer = document.querySelector('.slides-container');
        const presentationContainer = document.querySelector('.presentation-container');

        // 根据窗口宽度调整PPT预览区域的高度
        if (presentationContainer) {
            if (windowWidth < 768) {
                presentationContainer.style.height = '400px';
            } else {
                presentationContainer.style.height = '500px';
            }
        }

        // 重置缩放
        if (slidesContainer) {
            slidesContainer.style.transform = 'scale(1)';
        }
    }
}

// 工具函数：格式化时间
function formatTime(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

// 工具函数：节流
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const context = this;
        const args = arguments;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}